<template>
  <div class="server-list-container">
    <div class="content-wrapper">
      <page-header
        title="服务器管理"
        description="管理数据中心的服务器资源，包括服务器的基本信息、配置详情、运行状态等。可以进行服务器的添加、编辑、删除，以及查看服务器的详细信息。"
      >
        <el-input v-model="searchQuery" placeholder="搜索服务器..." class="search-input" clearable>
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </page-header>

      <!-- 添加/编辑服务器对话框 -->
      <server-form
        v-model:visible="dialogVisible"
        :server-data="currentServer"
        @success="handleFormSuccess"
      />

      <!-- 服务器列表 -->
      <el-table
        v-loading="loading"
        :data="filteredServers"
        style="width: 100%"
        :height="tableHeight"
      >
        <el-table-column prop="id" label="ID" width="80" fixed="left" />
        <el-table-column prop="hostname" label="主机名" min-width="200" fixed="left">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">
              {{ row.hostname }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="server_brand" label="品牌" width="140" show-overflow-tooltip />
        <el-table-column prop="server_model" label="型号" width="140" show-overflow-tooltip />
        <el-table-column prop="location" label="起始位置" width="140">
          <template #default="{ row }"> {{ row.location }} U </template>
        </el-table-column>
        <el-table-column prop="height" label="高度" width="100">
          <template #default="{ row }"> {{ row.height }} U </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sn" label="序列号" width="180" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right" align="center">
          <template #default="{ row }">
            <el-button type="primary" link @click.stop="handleView(row)">查看</el-button>
            <el-button type="primary" link @click.stop="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click.stop="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          :teleported="false"
          popper-class="pagination-select-dropdown"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <floating-action-button tooltip="添加服务器" @click="handleAdd" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { Plus, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { ServerInfo } from '@/api/types'
import { assetService } from '@/api/assetService'
import ServerForm from '@/components/asset/ServerForm.vue'
import { useRoomConfigStore } from '@/store/roomConfigStore'
import PageHeader from '@/components/common/PageHeader.vue'
import FloatingActionButton from '@/components/common/FloatingActionButton.vue'

const router = useRouter()
const roomConfigStore = useRoomConfigStore()
const loading = ref(false)
const servers = ref<ServerInfo[]>([])
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const currentServer = ref<ServerInfo>()
const tableHeight = ref(500)

// 过滤后的服务器列表
const filteredServers = computed(() => {
  if (!searchQuery.value) return servers.value
  const query = searchQuery.value.toLowerCase()
  return servers.value.filter(
    (server) =>
      server.hostname.toLowerCase().includes(query) ||
      server.sn.toLowerCase().includes(query) ||
      server.server_brand.toLowerCase().includes(query),
  )
})

// 获取服务器列表
const fetchServers = async () => {
  loading.value = true
  try {
    if (!roomConfigStore.currentRoom) {
      ElMessage.warning('请先选择机房')
      return
    }
    const response = await assetService.getServersByRoom(roomConfigStore.currentRoom.room_id, {
      page: currentPage.value,
      pageSize: pageSize.value,
    })
    if (Array.isArray(response)) {
      servers.value = response
      total.value = response.length
    } else if (response.items && Array.isArray(response.items)) {
      servers.value = response.items
      total.value = response.total || response.items.length
    }
  } catch (err) {
    console.error('获取服务器列表失败:', err)
    ElMessage.error('获取服务器列表失败')
  } finally {
    loading.value = false
  }
}

// 监听机房变化
watch(
  () => roomConfigStore.currentRoom?.room_id,
  (newRoomId) => {
    if (newRoomId) {
      currentPage.value = 1 // 重置页码
      fetchServers()
    } else {
      servers.value = []
      total.value = 0
    }
  },
  { immediate: true },
)

// 处理分页
const handleSizeChange = (size: number) => {
  pageSize.value = size
  fetchServers()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  fetchServers()
}

// 处理查看详情
const handleView = (server: ServerInfo) => {
  router.push(`/asset/server/${server.id}`)
}

// 处理添加
const handleAdd = () => {
  if (!roomConfigStore.currentRoom) {
    ElMessage.warning('请先配置机房')
    router.push('/settings/room-config')
    return
  }
  currentServer.value = undefined
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (server: ServerInfo) => {
  currentServer.value = server
  dialogVisible.value = true
}

// 处理删除
const handleDelete = async (server: ServerInfo) => {
  try {
    await ElMessageBox.confirm(`确认删除服务器 ${server.hostname}？`, '提示', {
      type: 'warning',
    })
    await assetService.deleteServer(server.id)
    ElMessage.success('删除成功')
    fetchServers()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除服务器失败:', error)
    }
  }
}

// 表单提交成功
const handleFormSuccess = () => {
  fetchServers()
}

// 计算表格高度
const updateTableHeight = () => {
  const vh = window.innerHeight
  tableHeight.value = vh - 64 - 48 - 52 - 32 - 24
}

// 监听窗口大小变化
onMounted(() => {
  updateTableHeight()
  window.addEventListener('resize', updateTableHeight)
  fetchServers()
})

onUnmounted(() => {
  window.removeEventListener('resize', updateTableHeight)
})

// 获取状态类型
const getStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    online: 'success',
    offline: 'danger',
    undeployed: 'info', // 添加未部署状态的样式
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    online: '在线',
    offline: '离线',
    undeployed: '未部署', // 添加未部署状态的文本
  }
  return textMap[status] || status
}
</script>

<style scoped lang="scss">
.server-list-container {
  height: 100%;

  .content-wrapper {
    height: 100%;
    display: flex;
    flex-direction: column;
    position: relative;
    padding-bottom: 48px;

    :deep(.el-table) {
      border: none;
      margin-bottom: 0;

      .el-table__body-wrapper {
        overflow-y: auto;
      }

      // 固定列阴影
      .el-table__fixed-right::before,
      .el-table__fixed::before {
        display: none;
      }

      // 表头样式
      .el-table__header {
        th {
          background-color: var(--el-fill-color-darker);
          &.is-leaf {
            border-bottom: 1px solid var(--el-border-color-lighter);
          }
          .cell {
            font-weight: 600;
            color: var(--el-text-color-regular);
            font-size: 14px;
          }
        }
      }

      &::after {
        display: none;
      }

      .el-table__cell {
        border-bottom: 1px solid var(--el-border-color-lighter);
      }

      // 优化行样式
      .el-table__row {
        &:hover {
          background-color: var(--el-fill-color-light);
        }

        .el-table__cell {
          border-bottom: 1px solid var(--el-border-color-lighter);
        }
      }

      .el-button--link {
        height: auto;
        padding: 4px 8px;
        font-size: 14px;
        font-weight: normal;
      }
    }

    .pagination {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      height: 32px;
      display: flex;
      justify-content: flex-end;
      padding: 8px 8px 8px 0;
      border-top: 1px solid var(--el-border-color-lighter);
      z-index: 1;

      :deep(.el-pagination) {
        white-space: nowrap;
        .el-select .el-input {
          margin: 0;
        }

        .el-select__popper {
          margin-top: -4px;
        }

        .el-select-dropdown {
          margin-top: 0 !important;
        }
      }
    }
  }
}
/* 新增全局样式（注意需要穿透scoped限制） */
:deep(.pagination-select-dropdown) {
  /* 强制弹窗向上展开 */
  top: auto !important;
  bottom: 100%;
  margin-bottom: 28px; /* 添加与分页器的间距 */

  /* 调整箭头方向 */
  .el-popper__arrow {
    top: 100%;
    bottom: auto;
    transform: translateY(-50%) rotate(180deg);
  }
}
</style>
